<template>
	<view class="page-container">
		<view class="logo"> Short Emby </view>
		<view class="login enter-area">
			<uni-forms ref="baseForm" :model="user" :rules="rules" label-width="90px" label-align="left">
				<uni-forms-item :label="$t('serverip')" name="serverip">
					<uni-easyinput v-model="user.serverip" :placeholder="$t('pleaseinput')" />
				</uni-forms-item>
				<uni-forms-item :label="$t('serverport')" name="serverport">
					<uni-easyinput v-model="user.serverport" type="number" :placeholder="$t('pleaseinput')" />
				</uni-forms-item>
				<uni-forms-item :label="$t('username')" name="username">
					<uni-easyinput v-model="user.username" :placeholder="$t('pleaseinput')" />
				</uni-forms-item>
				<uni-forms-item :label="$t('password')" name="password">
					<uni-easyinput v-model="user.password" type="password" :placeholder="$t('pleaseinput')" />
				</uni-forms-item>
			</uni-forms>
			<view class="register">
				<button type="primary" @click="submit('baseForm')">{{$t('signin')}}</button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/common/request'
	import store from '@/store/index.js'
	import {
		mapState
	} from 'vuex'

	export default {
		name: 'login',
		components: {},
		// computed: {
		//   ...mapState({
		//     userTmp: (state) => state.user
		//   })
		// },
		data() {
			return {
				user: {
					username: "",
					password: "",
					serverip: "",
					serverport: "",
					deviceName: "",
					deviceId: "",
					deviceVersion: "",
					userAvatar: "",
					userId: ""
				},
				rules: {
					username: {
						rules: [{
							required: true,
							errorMessage: 'The username cannot be empty'
						}]
					},
					serverip: {
						rules: [{
							required: true,
							errorMessage: 'The serverip cannot be empty'
						}]
					},
					serverport: {
						rules: [{
							required: true, // 补充必填验证
							errorMessage: 'The serverport cannot be empty'
						}]
					},
					password: {
						rules: [{
								required: true,
								errorMessage: 'The username cannot be empty'
							},
							{
								minLength: 6,
								maxLength: 20,
								errorMessage: 'The password must be between {minLength} and {maxLength}'
							}
						]
					}
				}
			}
		},
		methods: {
			validServerPort(rule, value, callback) {
				// 转换为数字
				const port = Number(value);
				// 校验是否为有效数字且在 1-65535 之间
				if (isNaN(port) || port < 1 || port > 65535) {
					callback('Port must be between 1 and 65535');
				} else {
					callback(); // 校验通过
				}
			},
			async submit(ref) {
				const deviceInfo = await this.getDeviceInfo()
				if (!deviceInfo) {
					toast.error('获取设备信息失败')
					return
				}
				this.user.deviceName = deviceInfo.deviceName
				this.user.deviceId = deviceInfo.deviceId
				this.$refs[ref]
					.validate()
					.then(async (res) => {
						store.commit('user', this.user)
						uni.setStorageSync('user', JSON.stringify(this.user))
						try {
							const systemInfo = await request.get('/emby/system/info/public')
							this.user.deviceVersion = systemInfo.Version
						} catch (error) {
							console.error('登录失败:', error)
							uni.showToast({
								title: '登录失败，请重试',
								icon: 'error',
							})
							throw error
						}
						store.commit('user', this.user)
						uni.setStorageSync('user', JSON.stringify(this.user))
						let loginParams = {
							"Username": this.user.username,
							"Pw": this.user.password
						}
						const userinfo = await request.post('/emby/Users/authenticatebyname', loginParams)
						const {
							AccessToken,
							User
						} = userinfo
						this.user.userId = User.Id
						let serverUrl = `${this.user.serverip}:${this.user.serverport}`
						if (!serverUrl.startsWith('http')) {
						  serverUrl = `http://${serverUrl}`
						}
						let avatar = `${serverUrl}/emby/Users/${User.Id}/Images/Primary`
						this.user.avatar = avatar
						uni.showToast({
							title: '登录成功',
							icon: 'success',
						})

						store.commit('token', AccessToken)
						store.commit('user', this.user)
						
						console.log("缓存数据："+JSON.stringify(this.user))
						uni.setStorageSync('token', AccessToken)
						uni.setStorageSync('user', JSON.stringify(this.user))

						uni.switchTab({
							url: '/pages/profile/profile'
						})
					})
					.catch((err) => {
						console.log('表单错误信息：', err)
					})
			},
			async register() {
				uni.navigateTo({
					url: '/pages/profile/register'
				})
			},
			async lastPassword() {
				uni.navigateTo({
					url: '/pages/profile/login'
				})
			},
			oauthFacebook() {
				uni.login({
					provider: 'facebook',
					success: function(loginRes) {
						// 登录成功
						uni.getUserInfo({
							provider: 'facebook',
							success: async function(info) {
								// 获取用户信息成功, info.authResult保存用户信息
								console.log(info)
								const userinfo = await request.post(
									'/oauth/facebook?_id=' + (store.state.user._id || ''),
									info.userInfo
								)

								const {
									token,
									user
								} = userinfo
								store.commit('token', token)
								store.commit('user', user)
								uni.setStorageSync('token', token)
								uni.setStorageSync('user', JSON.stringify(user))
								uni.switchTab({
									url: '/pages/profile/profile'
								})
							}
						})
					},
					fail: function(err) {
						// 登录授权失败
						// err.code是错误码
						uni.showToast({
							title: 'Authorization failed' + err.code,
							icon: 'none'
						})
					}
				})
			},
			oauthGoogle() {
				uni.login({
					provider: 'google',
					success: function(loginRes) {
						// 登录成功
						uni.getUserInfo({
							provider: 'google',
							success: async function(info) {
								// 获取用户信息成功, info.authResult保存用户信息
								const userinfo = await request.post(
									'/oauth/google?_id=' + (store.state.user._id || ''),
									info.userInfo
								)

								const {
									token,
									user
								} = userinfo
								store.commit('token', token)
								store.commit('user', user)
								uni.setStorageSync('token', token)
								uni.setStorageSync('user', JSON.stringify(user))
								uni.switchTab({
									url: '/pages/profile/profile'
								})
							}
						})
					},
					fail: function(err) {
						// 登录授权失败
						// err.code是错误码
						console.log(err)
						uni.showToast({
							title: 'Authorization failed' + err.code,
							icon: 'none'
						})
					}
				})
			},
			oauthApple() {
				uni.login({
					provider: 'apple',
					success: function(loginRes) {
						// 登录成功
						uni.getUserInfo({
							provider: 'apple',
							success: async function(info) {
								// 获取用户信息成功, info.authResult保存用户信息
								console.log('apple', info)
								const userinfo = await request.post(
									'/oauth/apple?_id=' + (store.state.user._id || ''),
									info.userInfo
								)

								const {
									token,
									user
								} = userinfo
								store.commit('token', token)
								store.commit('user', user)
								uni.setStorageSync('token', token)
								uni.setStorageSync('user', JSON.stringify(user))
								uni.switchTab({
									url: '/pages/profile/profile'
								})
							}
						})
					},
					fail: function(err) {
						// 登录授权失败
						// err.code是错误码
						console.log(err)
						uni.showToast({
							title: 'Authorization failed' + err.code,
							icon: 'none'
						})
					}
				})
			},
			// 获取设备信息
			getDeviceInfo() {
				return new Promise((resolve) => {
					// 在实际设备上使用plus获取设备信息
					if (typeof plus !== 'undefined') {
						plus.device.getInfo({
							success: (info) => {
								resolve({
									deviceName: info.model || 'Unknown Device',
									deviceId: info.uuid || plus.device.uuid,
								})
							},
							fail: () => {
								resolve(null)
							},
						})
					} else {
						// 模拟器环境下返回测试数据
						resolve({
							deviceName: 'Chrome+Android',
							deviceId: 'f31212e4-5ed5-4613-a27f-01afc7d2ca15',
						})
					}
				})
			}
		},
		created() {
			let userTmp1 = uni.getStorageSync('user')
			if(!userTmp1){
				return
			}
			let userTmp = JSON.parse(userTmp1)
			this.user.username = userTmp.username
			this.user.password = userTmp.password
			this.user.serverip = userTmp.serverip
			this.user.serverport = userTmp.serverport
		}
	}
</script>

<style lang="scss" scoped>
	.page-container {
		margin-top: 30%;

		.enter-area {
			padding-top: 75px;
			width: 87%;
			margin: 0 auto 60upx;

			.box {
				display: flex;
				align-items: center;
				min-height: 100upx;
				color: #000;
				border: 1px solid #eee;
				background-color: #fff;
				padding: 0 20upx;
				margin-bottom: 30upx;
				box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
			}
		}
	}

	.logo {
		font-size: 1.8rem;
		font-weight: bold;
		text-align: center;
		margin: 50px 0 20px;
	}

	.login {
		padding: 20px;
		padding-bottom: 0;

		button {
			line-height: 2.3;
			margin: 0 50px;
			height: 30pt;
			border-radius: 6pt;
		}
	}

	.register {
		padding: 20px 50px;
		font-size: 12px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.social {
		padding: 0 40px;
		font-size: 10px;

		.but {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 30pt;
			// width:130pt;
			margin: 20px 30px;
			font-size: 14px;
			border-radius: 6pt;

			.icon {
				margin-right: 10px;
			}
		}

		.google {
			color: #fff;
			background-color: #ea4336;
		}
	}

	.bottom {
		font-size: 8px;
		text-align: center;
		color: #888;

		a {
			font-weight: bold;
			color: #fff;
			padding: 0 3px;
			text-decoration: underline;
		}
	}
</style>